package com.entity.weixin;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;

import javax.servlet.http.HttpServletRequest;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class PayCommonUtil {

    /**
     * 是否签名正确,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。
     * 
     * @return boolean
     */
    public static boolean isTenpaySign(String characterEncoding, SortedMap<Object, Object> packageParams,
	    String API_KEY) {
	StringBuffer sb = new StringBuffer();
	Set es = packageParams.entrySet();
	Iterator it = es.iterator();
	while (it.hasNext()) {
	    Map.Entry entry = (Map.Entry) it.next();
	    String k = (String) entry.getKey();
	    String v = (String) entry.getValue();
	    if (!"sign".equals(k) && null != v && !"".equals(v)) {
		sb.append(k + "=" + v + "&");
	    }
	}

	sb.append("key=" + API_KEY);

	// 算出摘要
	String mysign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toLowerCase();
	String tenpaySign = ((String) packageParams.get("sign")).toLowerCase();

	// System.out.println(tenpaySign + " " + mysign);
	return tenpaySign.equals(mysign);
    }

    /**
     * @author
     * @date 2016-4-22
     * @Description：sign签名
     * @param characterEncoding
     *            编码格式
     * @param parameters
     *            请求参数
     * @return
     */
    public static String createSign(String characterEncoding, SortedMap<Object, Object> packageParams, String API_KEY) {
	StringBuffer sb = new StringBuffer();
	Set es = packageParams.entrySet();
	Iterator it = es.iterator();
	while (it.hasNext()) {
	    Map.Entry entry = (Map.Entry) it.next();
	    String k = (String) entry.getKey();
	    String v = (String) entry.getValue();
	    if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
		sb.append(k + "=" + v + "&");
	    }
	}
	sb.append("key=" + API_KEY);
	String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
	return sign;
    }

    /**
     * @author
     * @date 2016-4-22
     * @Description：将请求参数转换为xml格式的string
     * @param parameters
     *            请求参数
     * @return
     */
    public static String getRequestXml(SortedMap<Object, Object> parameters) {
	StringBuffer sb = new StringBuffer();
	sb.append("<xml>");
	Set es = parameters.entrySet();
	Iterator it = es.iterator();
	while (it.hasNext()) {
	    Map.Entry entry = (Map.Entry) it.next();
	    String k = (String) entry.getKey();
	    String v = (String) entry.getValue();
	    if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k) || "sign".equalsIgnoreCase(k)) {
		sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">");
	    } else {
		sb.append("<" + k + ">" + v + "</" + k + ">");
	    }
	}
	sb.append("</xml>");
	return sb.toString();
    }

    /**
     * 取出一个指定长度大小的随机正整数.
     * 
     * @param length
     *            int 设定所取出随机数的长度。length小于11
     * @return int 返回生成的随机数。
     */
    public static int buildRandom(int length) {
	int num = 1;
	double random = Math.random();
	if (random < 0.1) {
	    random = random + 0.1;
	}
	for (int i = 0; i < length; i++) {
	    num = num * 10;
	}
	return (int) ((random * num));
    }

    /**
     * 获取当前时间 yyyyMMddHHmmss
     * 
     * @return String
     */
    public static String getCurrTime() {
	Date now = new Date();
	SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");
	String s = outFormat.format(now);
	return s;
    }

    public static Long getCurrentTimeMillis() {
	return System.currentTimeMillis() / 1000;
    }

    /**
     * @description 将xml字符串转换成map
     * @param xml
     *            支付的返回的XML
     * @return Map
     */
    public static Map<String, String> readStringXmlOut(String xml) {
	Map<String, String> map = new HashMap<String, String>();
	Document doc = null;
	try {
	    doc = DocumentHelper.parseText(xml); // 将字符串转为XML
	    Element rootElt = doc.getRootElement(); // 获取根节点
	    List<Element> list = rootElt.elements();// 获取根节点下所有节点
	    for (Element element : list) { // 遍历节点
		map.put(element.getName(), element.getText()); // 节点的name为map的key，text为map的value
	    }
	} catch (DocumentException e) {
	    e.printStackTrace();
	} catch (Exception e) {
	    e.printStackTrace();
	}
	return map;
    }

    public static String getIpAddr(HttpServletRequest request) {
	String ipAddress = null;
//	System.out.println(request.getLocalAddr());
//	ipAddress = request.getRemoteAddr();
	System.out.println(ipAddress);
	System.out.println(request);
	ipAddress = request.getHeader("x-forwarded-for");
	System.out.println(ipAddress);
	if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
	    ipAddress = request.getHeader("Proxy-Client-IP");
	    System.out.println(ipAddress);
	}
	if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
	    ipAddress = request.getHeader("WL-Proxy-Client-IP");
	    System.out.println(ipAddress);
	}
	if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
	    ipAddress = request.getRemoteAddr();
	    if (ipAddress.equals("127.0.0.1")) {
		// 根据网卡取本机配置的IP
		InetAddress inet = null;
		try {
		    inet = InetAddress.getLocalHost();
		} catch (UnknownHostException e) {
		    e.printStackTrace();
		}
		ipAddress = inet.getHostAddress();
	    }
	}
	// 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
	if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
	    if (ipAddress.indexOf(",") > 0) {
		ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
		System.out.println(ipAddress);
	    }
	}
	System.out.println(ipAddress);
	return ipAddress;
    }

}